package com.fengplus.demo.controller;

import com.fengplus.demo.entity.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/normal")
public class NormalController {

//    public static final String PROVIDER_URL = "http://localhost:8203";
    public static final String PROVIDER_SERVICE = "EUREKA-PROVIDER-SERVICE";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/a")
    public String a() {
        return restTemplate.getForObject("http://" + PROVIDER_SERVICE + "/normal/a", String.class);
    }

    @GetMapping("/b")
    public CommonResult b() {
        ResponseEntity<CommonResult> entity = restTemplate
            .getForEntity("http://" + PROVIDER_SERVICE + "/normal/b", CommonResult.class);
        if(entity.getStatusCode().is2xxSuccessful()) {
            return entity.getBody();
        }else{
            return new CommonResult(400, "操作失败", null);
        }
    }

    @GetMapping("/c")
    public Map<String, Object> c() {
        // 服务列表
        List<String> services = discoveryClient.getServices();
        List<ServiceInstance> instances = discoveryClient.getInstances(PROVIDER_SERVICE);
        Map<String, Object> map = new HashMap();
        map.put("services", services);
        map.put("instances", instances);

        return map;
    }

}
